using Microsoft.AspNetCore.Mvc;     // 因为ControllerBase等需要引入
using MyWebApi.Api.Entity;      // 因为Users表需要引入
using System.Collections.Generic;   // 因为泛型需要引入
using System.Linq;     // 因为Where 引入之后我们可以使用一种类似SQL的语法来查询任何形式的数据
using System;
using MyWebApi.Api.Repository;
using MyWebApi.Api.ParamModel;
using MyWebApi.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;

namespace MyWebApi.Api.Controllers
{
    // 特性
    // [Authorize]  // [Authorize]下的所有Api接口如：查询、删除、创建用户不能匿名访问，需要Token令牌才可访问
    [ApiController]
    [Route("[controller]")]

    public class JournalismController : ControllerBase
    {
        //使用实现的接口操作新闻表
        // 用户表
        private IRepository<Users> _usersRespository;
        // 新闻表
        private IRepository<Journalism> _journalismRepository;
        // 新闻图表
        private IRepository<NewsCoverPicture> _newsCoverPicture;
        // 阅读量表
        private IRepository<NumberNewsReading> _numberNewsReading;
        // 点赞表
        private IRepository<NewsStoryPraised> _newsStoryPraised;
        // 评论表
        private IRepository<NewsComment> _newsComment;

        // 初始化新闻控制器
        public JournalismController(IConfiguration configuration,
        IRepository<Journalism> journalismRepository,
        IRepository<NewsCoverPicture> newsCoverPicture,
        IRepository<NumberNewsReading> numberNewsReading,
        IRepository<NewsStoryPraised> newsStoryPraised,
        IRepository<Users> usersRespository,
        IRepository<NewsComment> newsComment
        )
        {
            // 新闻表
            _journalismRepository = journalismRepository;
            // 新闻图表
            _newsCoverPicture = newsCoverPicture;
            // 阅读量表
            _numberNewsReading = numberNewsReading;
            // 点赞表
            _newsStoryPraised = newsStoryPraised;
            // 用户表
            _usersRespository = usersRespository;
            // 评论表
            _newsComment = newsComment;
        }


        // 添加新闻
        [HttpPost]
        public dynamic postAddJournalism(JournalismModel model)
        {
            // 获取需要存入数据库的值
            // 新闻标题
            var newsTitle = model.NewsTitle;

            // 新闻发布人Id
            var pressReleaseUserId = model.PressReleaseUserId;

            // 新闻内容
            var newsContent = model.NewsContent;

            // 判断新闻图片是否为空
            if (string.IsNullOrEmpty(model.SurfacePlot))
            {
                // 为空则等于暂无
                model.SurfacePlot = "默认图片";
            }
            else
            {
                // 不为空则等于用户上传的图片
                model.SurfacePlot = model.SurfacePlot;
            }
            var surfacePlot = model.SurfacePlot;

            // 是否推荐
            var isRecommend = model.IsRecommend;

            // 判断备注是否为空
            if (string.IsNullOrEmpty(model.Remark))
            {
                // 为空则等于暂无
                model.Remark = "暂无";
            }
            else
            {
                // 不为空则等于用户填入的备注
                model.Remark = model.Remark;
            }
            // 备注 
            var remark = model.Remark;
            // 判断新闻标题和内容是否为空
            if (!string.IsNullOrEmpty(newsTitle) && !string.IsNullOrEmpty(newsContent))
            {
                // 数据不为空
                // 新闻表插入数据
                var journalism = new Journalism
                {
                    NewsTitle = newsTitle,
                    PressReleaseUserId = pressReleaseUserId,
                    NewsContent = newsContent,
                    SurfacePlot = surfacePlot,
                    IsRecommend = isRecommend,
                    Remark = remark
                };
                _journalismRepository.Insert(journalism);

                // 返回前端数据
                var res = new
                {
                    Code = 1000,
                    Data = journalism,
                    Msg = "新闻发布成功"
                };
                return JsonHelper.Serialize(res);
            }
            else
            {
                // 数据为空
                // 返回前端数据
                var res = new
                {
                    Code = 1001,
                    Data = "新闻标题和内容不能为空",
                    Msg = "新闻标题和内容不能为空"
                };
                return JsonHelper.Serialize(res);
            }

        }

        // 查询所有新闻(根据更新时间倒序)
        [HttpGet]
        public dynamic selectAllJournalism()
        {

            var allJournalism = _journalismRepository.Table.OrderByDescending(x => x.UpdatedTime).Where(x => x.IsDeleted == false);

            var res = new
            {
                Code = 1000,
                Data = allJournalism,
                Msg = "获取所有新闻成功（根据更新时间倒序）"
            };
            return JsonHelper.Serialize(res);

        }


        // 查询需要的新闻条数(根据更新时间倒序)
        [HttpGet, Route("select")]
        public dynamic selectGetNumberJournalism(JournalismModel model)
        {

            var allJournalism = _journalismRepository.Table.OrderByDescending(x => x.CreatedTime).Where(x => x.IsDeleted == false).ToList();
            var filterJournalism = allJournalism.Skip(0).Take(model.Quantity).ToList();
            var res = new
            {
                Code = 1000,
                Data = filterJournalism,
                Msg = string.Format("获取{0}条新闻成功（根据更新时间倒序）", model.Quantity)
            };
            return JsonHelper.Serialize(res);

        }


        // 根据id查询数据(可添加阅读量)
        [HttpGet("{id}")]
        public dynamic GetIdJournalism(int id)
        {
            var allJournalism = _journalismRepository.Table.Where(x => x.Id == id && x.IsDeleted == false);

            // 添加阅读量
            var numberNewsReading = new NumberNewsReading
            {
                NewsId = id
            };
            _numberNewsReading.Insert(numberNewsReading);

            var res = new
            {
                Code = 1000,
                Data = allJournalism,
                Msg = string.Format("获取Id为{0}新闻成功", id)
            };
            return JsonHelper.Serialize(res);
        }


        // 查询新闻的阅读量最多的排名
        [HttpGet, Route("countreading")]
        public dynamic countreading(JournalismModel model)
        {
            // 查询未删除的阅读量数据
            var numberNewsReading = _numberNewsReading.Table.Where(x => x.IsDeleted == false).ToList(); ;
            // 分组倒序查询每个新闻的阅读量
            var query = (from t in numberNewsReading
                         group t by new { t.NewsId }
                         into grp
                         select new
                         {
                             grp.Key.NewsId,
                             readingQuantity = grp.Count()
                         }).OrderByDescending(x => x.readingQuantity);

            // 阅读量最高的排名
            var filterCountReading = query.Skip(0).Take(model.Quantity).ToList();
            // 所有新闻
            var allJournalism = _journalismRepository.Table.ToList();
            // 点赞表
            var newsStoryPraised = _newsStoryPraised.Table.ToList();


            // 连接查询两个表
            var journalismJoinCountReading = allJournalism.Join(filterCountReading, journalism => journalism.Id, countReading => countReading.NewsId, (journalism, countReading) => new
            {
                journalismId = journalism.Id,
                journalismName = journalism.NewsTitle,      // 新闻标题
                countReading = countReading.readingQuantity,    // 阅读量
                NewsContent = journalism.NewsContent,  // 内容
                SurfacePlot = journalism.SurfacePlot,    // 图片
                PressReleaseUserId = journalism.PressReleaseUserId,    // 发布人id
                Remark = journalism.Remark,    // 备注
                CreatedTime = journalism.CreatedTime  // 创建时间
            });


            var res = new
            {
                Code = 1000,
                Data = journalismJoinCountReading,
                Msg = string.Format("查询阅读量前{0}名新闻成功", model.Quantity)
            };
            return JsonHelper.Serialize(res);

        }


        // 点赞功能
        [HttpPost, Route("storypraised")]
        public dynamic storypraised(JournalismModel model)
        {
            // 查询所有用户
            var users = _usersRespository.Table;
            // 查询用户id是否存在
            var filterUser = users.Where(x =>
                       x.Id == model.GiveALikeUserId
                 ).ToList();
            if (filterUser.Count != 0)
            {
                // 用户存在

                // 查询点赞表
                var clickGood = _newsStoryPraised.Table;
                // 判断是否重复点赞
                var isAgainClickGood = clickGood.Where(x => x.GiveALikeUserId == model.GiveALikeUserId && x.NewsId == model.JournalismId).ToList();
                if (isAgainClickGood.Count == 0)
                {
                    // 没有重复
                    var newsStoryPraised = new NewsStoryPraised
                    {
                        // 插入数据到点赞表
                        NewsId = model.JournalismId,
                        GiveALikeUserId = model.GiveALikeUserId
                    };
                    _newsStoryPraised.Insert(newsStoryPraised);

                    // 点赞成功
                    var res = new
                    {
                        Code = 1000,
                        Data = newsStoryPraised,
                        Msg = "点赞成功"
                    };
                    return JsonHelper.Serialize(res);
                }
                else
                {
                    // 重复点赞
                    var res = new
                    {
                        Code = 1001,
                        Msg = "重复点赞"
                    };
                    return JsonHelper.Serialize(res);
                }
            }
            else
            {
                // 用户不存在
                var res = new
                {
                    Code = 1001,
                    Msg = "用户不存在或没有登录"
                };
                return JsonHelper.Serialize(res);
            }

        }


        // 某条新闻的点赞统计
        [HttpGet, Route("clickgoodtatistics/{id}")]
        public dynamic clickgoodtatistics(int id)
        {
            // 查询点赞表
            var numberNewsReading = _newsStoryPraised.Table.ToList(); ;
            // 查询某个新闻的点赞总数
            var query = (from t in numberNewsReading
                         group t by new { t.NewsId }
                         into grp
                         select new
                         {
                             grp.Key.NewsId,
                             clickGoodCount = grp.Count()
                         }).OrderByDescending(x => x.clickGoodCount).Where(x => x.NewsId == id);

            // 点赞成功
            var res = new
            {
                Code = 1000,
                Data = query,
                Msg = string.Format("获取id为{0}的点赞数量成功", id)
            };
            return JsonHelper.Serialize(res);
        }


        // 某条新闻的评论统计
        [HttpGet, Route("commenttatistics/{id}")]
        public dynamic commenttatistics(int id)
        {
            // 查询评论表
            var newsComment = _newsComment.Table.ToList(); ;
            // 查询某个新闻的评论总数
            var query = (from t in newsComment
                         group t by new { t.NewsId }
                         into grp
                         select new
                         {
                             grp.Key.NewsId,
                             newsComment = grp.Count()
                         }).OrderByDescending(x => x.newsComment).Where(x => x.NewsId == id);

            // 点赞成功
            var res = new
            {
                Code = 1000,
                Data = query,
                Msg = string.Format("获取id为{0}的评论数量成功", id)
            };
            return JsonHelper.Serialize(res);
        }

        // 某条新闻的阅读统计
        [HttpGet, Route("readstatistics/{id}")]
        public dynamic readstatistics(int id)
        {
            // 查询评论表
            var numberNewsReading = _numberNewsReading.Table.ToList(); ;
            // 查询某个新闻的评论总数
            var query = (from t in numberNewsReading
                         group t by new { t.NewsId }
                         into grp
                         select new
                         {
                             grp.Key.NewsId,
                             numberNewsReading = grp.Count()
                         }).OrderByDescending(x => x.numberNewsReading).Where(x => x.NewsId == id);

            // 点赞成功
            var res = new
            {
                Code = 1000,
                Data = query,
                Msg = string.Format("获取id为{0}的阅读数量成功", id)
            };
            return JsonHelper.Serialize(res);
        }









































    }

}